package com.cl.code.database.mybatis.module.sql.condition;

import com.cl.code.database.mybatis.constant.CLMybatisConstants;
import com.cl.code.database.mybatis.module.sql.Fn;
import com.cl.code.database.mybatis.module.sql.operator.LogicSqlOperator;
import com.cl.code.database.mybatis.module.sql.operator.SqlExpression;
import org.apache.ibatis.parsing.GenericTokenParser;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @author chengliang
 * @since 1.0.0
 */
public class SingleConditionItem<Entity> extends ConditionItem {

    private final String column;

    private final SqlExpression sqlExpression;

    private final ParamValue[] values;

    public SingleConditionItem(LogicSqlOperator andOr, String column, SqlExpression sqlExpression, ParamValue... values) {
        super(andOr);
        this.column = column;
        this.sqlExpression = sqlExpression;
        this.values = values;
    }

    @Override
    public String getSql() {
        String expression = sqlExpression.getExpression();
        String sql = new GenericTokenParser(CLMybatisConstants.PARAM_START, CLMybatisConstants.PARAM_END, token -> {
            if (CLMybatisConstants.COLUMN_NAME.equals(token)) {
                return column;
            } else if (CLMybatisConstants.VALUE_NAME.equals(token)) {
                return values[0].getParamPath();
            } else if (CLMybatisConstants.VALUES_NAME.equals(token)) {
                return Arrays.stream(values).map(ParamValue::getParamPath).collect(Collectors.joining(","));
            } else if (CLMybatisConstants.VALUE_FIRST_NAME.equals(token)) {
                return values[0].getParamPath();
            } else if (CLMybatisConstants.VALUE_SECOND_NAME.equals(token)) {
                return values[1].getParamPath();
            }
            return token;
        }).parse(expression);
        return super.andOr.getOperator() + sql;
    }

}
